//
//  TrailerSegment.m
//  NewsMaker Touch
//
//  Created by Reisen on 9/26/14.
//  Copyright (c) 2014 Reisen. All rights reserved.
//

#import "TrailerSegment.h"
#import <AVFoundation/AVFoundation.h>
#import "Utility.h"
#import "TalkDefine.h"

@implementation TrailerSegment

-(void)save
{
    /*
    NSMutableDictionary* dict = [NSMutableDictionary new];
    
    if(self.selectedVideo != nil)
        [dict setObject:self.selectedVideo forKey:@"selectedVideo"];
    
    [dict writeToFile:[[self fullPath] stringByAppendingPathComponent:@"segment.plist"] atomically:YES];
     */
}

-(void)load
{
    NSString* path = [self.root stringByAppendingPathComponent:self.src];

    //    NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableContainers error:nil];
    
    self.selectedVideo = [dict objectForKey:@"selectedVideo"];
}

-(BOOL)canPreview
{
    return YES;
}

-(void)initializePreview
{
    [self.currentPreviewLayer.layoutView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    [self load];
    
    NSString* folderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Trailers"];
    
    NSString* filepath = [folderPath stringByAppendingPathComponent:self.selectedVideo];
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:filepath])
    {
        filepath = [self.fileRoot stringByAppendingPathComponent:self.selectedVideo];
    }

    TLDebugS(@"Load video from %@", filepath);

    
    NSURL *fileURL = [NSURL fileURLWithPath:filepath];
    
    AVPlayerItem* item = [AVPlayerItem playerItemWithURL:fileURL];
    
    player = [AVPlayer playerWithPlayerItem:item];
    player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
    
    layer = [AVPlayerLayer playerLayerWithPlayer:player];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.currentPreviewLayer.bounds;
    [self.currentPreviewLayer.videoView.layer addSublayer:layer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoCompleted:) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
    
  //  [player addObserver:self forKeyPath:@"status" options:0 context:nil];
    
}

/*
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if(object == player && [keyPath isEqualToString:@"status"])
    {
        if(player.status == AVPlayerStatusReadyToPlay)
        {
            self.currentPreviewLayer.layoutView.hidden = YES;
            
            [player removeObserver:self forKeyPath:@"status"];
        }
    }
}
 */
-(void)videoCompleted:(NSNotification*)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.currentPreviewLayer playNextSegment];
    
    [layer setPlayer:nil];
    player = nil;
    
    [layer removeFromSuperlayer];
    layer = nil;
}

-(void)play
{
    [player play];
}

-(void)pause
{
    [player pause];
}

-(void)stop
{
    [player pause];
    
    [self videoCompleted:nil];
}


-(void) encodeVideo
{
    //Autoskip!
    self.progress = 1;
    [self.encodingDelegate performSelector:self.encodingCompleted withObject:self];
}


-(NSString*)videoInformation
{
    NSString* folderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Trailers"];
    
    NSString* filepath = [folderPath stringByAppendingPathComponent:self.selectedVideo];
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:filepath])
    {
        filepath = [self.fileRoot stringByAppendingPathComponent:self.selectedVideo];
    }
    
    TLDebugS(@"Add video: %@", filepath);
    
    return filepath;
}

-(NSMutableArray*)audioInformationWithStart:(float)start
{
    NSMutableArray* arr = [NSMutableArray array];
    [arr addObject:@{@"path": [self videoInformation], @"start":[NSNumber numberWithFloat:start], @"duration":[NSNumber numberWithFloat:-1], @"track":[NSNumber numberWithInt:0]}];
    
    return arr;
}

-(float)getDuration
{
    NSString* folderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Trailers"];
    
    NSString* filepath = [folderPath stringByAppendingPathComponent:self.selectedVideo];
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:filepath])
    {
        filepath = [self.fileRoot stringByAppendingPathComponent:self.selectedVideo];
    }

    TLDebugS(@"Load video from %@", filepath);

    NSURL *fileURL = [NSURL fileURLWithPath:filepath];
    
    AVPlayerItem* item = [AVPlayerItem playerItemWithURL:fileURL];
    
    return CMTimeGetSeconds([[item asset] duration]);
}
@end
